// 地区模糊查询
import React from 'react';
import { Select, Spin } from 'antd';
import HOCSelect from '@/components/AntDesign/Select';
import Debounce from 'lodash-decorators/debounce';
import PropTypes from 'prop-types';
import { fetchAssoCustomer } from '@/services/api';

const { Option } = Select;

class AssociatedCustomerWithState extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      assoCustomerList: [],
      loading: false,
    };
  }

  // 在这里先获取上级如果有传过来value先去获取一下数据，如果没有传则不用
  async componentDidMount() {
    const { value } = this.props;
    const queryVal = value?.title;
    if (!queryVal) {
      return false;
    }
    this.fetchAssoCustomer(queryVal);
  }

  /**
   *模糊查询关联客户名称
   * @param {string} value 模糊查询所需值
   * Debounce 防抖
   */
  @Debounce(1000)
  async fetchAssoCustomer(value) {
    if (value.trim().length) {
      this.setState({ loading: true });
      try {
        const response = await fetchAssoCustomer({ name: value.trim() });
        this.setState({
          assoCustomerList: Array.isArray(response.data) ? response.data : [],
        });
      } catch (e) {
        console.error(e);
      } finally {
        this.setState({ loading: false });
      }
    }
  }

  render() {
    const { handleChange, value, labelInValue, ...rest } = this.props;
    const { loading, assoCustomerList = [] } = this.state;
    return (
      <HOCSelect
        placeholder="请输入关键字检索"
        {...rest}
        showSearch
        labelInValue={labelInValue}
        value={labelInValue ? value : value?.title}
        showArrow={false}
        onSearch={val => this.fetchAssoCustomer(val)}
        notFoundContent={loading ? <Spin size="small" /> : '暂无数据'}
        onSelect={(changeValue, options) => handleChange(changeValue, options)}
      >
        {assoCustomerList.map(item => (
          <Option key={item.mdCustId} title={item.name}>
            {item.name}
          </Option>
        ))}
      </HOCSelect>
    );
  }
}
AssociatedCustomerWithState.defaultProps = {
  handleChange: () => {}, // 选择关联客户
  labelInValue: false, // 是否为labelInvalue形式
};
AssociatedCustomerWithState.propTypes = {
  handleChange: PropTypes.func,
  labelInValue: PropTypes.bool,
};
export default AssociatedCustomerWithState;
